<template>
  <view class="container page-bottom-fixed">
    <view class="header">
      <!-- 搜索 -->
      <view :class="'search wh-auto '">
        <view class="search-content oh bg-gray flex-row">
          <uni-icons class="spi" type="search" size="16" color="#b7b7b7"></uni-icons>
          <input type="text" confirm-type="search" placeholder="搜索内容" class="wh-auto cr-888" @confirm="search_input_event" />
        </view>
      </view>
    </view>

	<block v-if="site_for_led == 1">
		<!-- 筛选栏 -->
		<view class="filter-section">
		  <!-- 行业分类横向滚动 -->
		  <scroll-view class="industry-scroll" scroll-x="true" show-scrollbar="false">
		    <view class="industry-list">
		      <view
		        v-for="item in industryOptions"
		        :key="item.id"
		        class="industry-item"
		        :class="{ active: selectedIndustry === item.id }"
		        @tap="selectIndustry2(item.id)"
		      >
		        {{ item.name }}
		      </view>
		    </view>
		  </scroll-view>
		  
		  <!-- 智能排序横向平铺 -->
		  <view class="sort-list">
		    <view
		      v-for="item in sortOptions"
		      :key="item.value"
		      class="sort-item"
		      :class="{ active: selectedSort === item.value }"
		      @tap="selectSort2(item)"
		    >
		      {{ item.name }}
		    </view>
		  </view>
		</view>
	</block>
    <block v-else>
		<!-- 筛选栏 -->
		<view class="filter-bar" v-if="industryOptions.length > 0">
			<!-- 行业分类筛选 -->
			<view class="filter-item" @tap="toggleIndustryFilter">
				<text v-if="selectedIndustry == 0">行业</text>
				<text v-else>{{ industryOptionsName}}</text>
				<view class="arrow-down-small"></view>
			</view>
		  
		  <!-- 地区筛选 - 点击跳转到城市选择页面 -->
		  <view class="filter-item" @tap="goToCitySelect">
		    <text>{{ city_name }}</text>
		    <view class="arrow-down"></view>
		  </view>
		  
		  <!-- 智能排序筛选 -->
		  <view class="filter-item" @tap="toggleSortFilter">
		    <text>{{ selectedSortName }}</text>
		    <view class="arrow-down"></view>
		  </view>
		</view>
		
		<!-- 行业分类筛选弹窗 -->
		<view v-if="showIndustryFilter" class="filter-popup" @tap="closeIndustryFilter">
		  <view class="filter-popup-content" @tap.stop>
		    <view
		      v-for="item in industryOptions"
		      :key="item"
		      class="filter-option"
		      :class="{ active: selectedIndustry === item.id }"
		      @tap="selectIndustry(item.id)"
		    >
		      {{ item.name }}
		    </view>
		  </view>
		</view>
		
		<!-- 智能排序筛选弹窗 -->
		<view v-if="showSortFilter" class="filter-popup" @tap="closeSortFilter">
		  <view class="filter-popup-content" @tap.stop>
		    <view
		      v-for="item in sortOptions"
		      :key="item.value"
		      class="filter-option"
		      :class="{ active: selectedSort === item.value }"
		      @tap="selectSort(item)"
		    >
		      {{ item.name }}
		    </view>
		  </view>
		</view>
	</block>

    <view class="padding-top-main">
      <!-- 使用卡片组件渲染置顶数据列表 -->
      <block v-if="top_data_list.length > 0">
        <block v-for="(item, index) in top_data_list" :key="item.id">
          <component-card-item :propConfig="data_base" :propData="item" propSpec="1" @toggle-favorite="handleToggleFavorite"></component-card-item>
        </block>
      </block>

      <!-- 使用卡片组件渲染普通名片列表 -->
      <block v-if="data_list.length > 0">
        <block v-for="(item, index) in data_list" :key="item.id">
          <component-card-item :propConfig="data_base" :propData="item" @toggle-favorite="handleToggleFavorite"></component-card-item>
        </block>
      </block>
    </view>

    <!-- 将底部组件移到view内部 -->
    <component-classinfo-footer :propBaseData="data_base"></component-classinfo-footer>
  </view>
</template>

<script>
const app = getApp();
import componentClassinfoFooter from '../public/footer';
import componentCardItem from '../public/card-item';
import { classinfo_base_info } from '@/pages/fcc/classinfo/public/common.js';

var common_static_url = app.globalData.get_static_url('common');
var static_url_mini = app.globalData.get_static_url('classinfo', true);

export default {
  name: 'CompanyList',
  data() {
    return {
      common_static_url: common_static_url,
      static_url_mini: static_url_mini,
      data_bottom_line_status: false,
      data_list_loding_status: '',
      data_list: [],
      data_is_loading: 0,
      data_total: 0,
      data_page_total: 0,
      data_page: 1,
      data_base: null,
      city_id: 0,
      city_name: '定位',
      load_status: 0,
      params: null,
      post_data: {},
      top_ids: '',
      top_data_list: [],
      scrollTop: 0,
      showSortFilter: false,
      selectedSort: 'default',
      sortOptions: [
        { value: 'distance', name: '距离' },
        { value: 'id', name: '最新' },
        { value: 'default', name: '推荐' }
      ],
		showIndustryFilter: false,
		selectedIndustry: 0,
		industryOptionsName: '行业',
		industryOptions: [],
		site_for_led: app.globalData.data.site_for_led,
    }
  },
  computed: {
    selectedSortName() {
      const item = this.sortOptions.find(s => s.value === this.selectedSort);
      return item ? item.name : '智能排序';
    }
  },
  components: {
    componentClassinfoFooter,
    componentCardItem,
  },
  mounted() {
    // 默认推荐排序
    this.selectedSort = this.sortOptions[2].value;
  },
  onLoad(params) {
    params = app.globalData.launch_params_handle(params);

    this.params = params;
    this.post_data = { wd: params.keywords || '' };
    
    if (params.city_id) {
      this.city_id = parseInt(params.city_id);
    }

    this.init();
  },
  onShow() {
    app.globalData.page_event_onshow_handle();

    if (this.load_status == 1) {
      this.city_chose_handle();
    }
  },
  onPullDownRefresh() {
    this.resetAndReload();
  },
  onPageScroll(e) {
    this.scrollTop = e.scrollTop;
    if (e.scrollTop > 100) {
      this.get_data_list();
    }
  },
  methods: {
    resetAndReload() {
      this.data_page = 1;
      this.data_list = [];
      this.get_data_list(1);
    },
    
    selectSort2(item) {
      this.selectedSort = item.value;
      this.resetAndReload();
    },
    
    selectIndustry2(industry) {
      this.selectedIndustry = industry;
      this.resetAndReload();
    },
	
	selectFilterOption(type, value) {
      if (type === 'sort') {
        this.selectedSort = value;
        this.showSortFilter = false;
      } else if (type === 'industry') {
        this.selectedIndustry = value;
		var temp_data = this.industryOptions;
		for(var i in temp_data)
		{
			if(temp_data[i]['id'] == value)
			{
				this.industryOptionsName = temp_data[i]['name'];
				break;
			}
		}
        this.showIndustryFilter = false;
      }
      this.resetAndReload();
    },
    
    selectSort(item) {
      this.selectFilterOption('sort', item.value);
    },
    
    selectIndustry(industry) {
      this.selectFilterOption('industry', industry);
							
    },

    init() {
      classinfo_base_info()
        .then(data => {
          this.init_before(data)
            .then(() => {
              const cityInfo = uni.getStorageSync('user_city_info');
              if (cityInfo) {
                this.city_id = cityInfo.city_id;
                this.city_name = cityInfo.city_name;
                this.data_list = [];
                this.data_page = 1;
                uni.setStorageSync('is_have_load_search', 1);
              }
              this.get_data();
            });
        });
    },
    
    init_before(data) {
      return new Promise((resolve) => {
        this.data_base = data;
        
        if (this.city_id > 0) {
          uni.setStorageSync('user_city_info', {
            city_id: this.city_id,
            city_name: ''
          });
        }
        resolve();
      });
    },
    
    city_chose_handle() {
      const isChoseCity = uni.getStorageSync('is_chose_city');
      if (!isChoseCity) return;
      
      const cityInfo = uni.getStorageSync('user_city_info');
      if (cityInfo) {
        this.city_id = cityInfo.city_id;
        this.city_name = cityInfo.city_name;
        this.resetAndReload();
      }
    },
    
    get_data() {
      const post_data = this.request_map_handle();
      
      uni.request({
        url: app.globalData.get_request_url("cardinit", "index", "classinfo"),
        method: 'POST',
        data: post_data,
        dataType: 'json',
        success: res => {console.log(res);
          uni.stopPullDownRefresh();
          
          if (res.data.code == 0) {
            const data = res.data.data;
            const topInfo = data.top_info || {};
            
            Object.assign(this, {
              search_map_info: data.search_map_info || [],
              search_map_list: { county_list: data.county_list || [] },
              load_status: 1,
              top_data_list: topInfo.data || [],
              top_ids: topInfo.ids || '',
              city_name: data.city_name || this.city_name,
              industryOptions: [{ id: 0, name: '全部' }, ...(data.category_list || [])]
            });
            
            this.get_data_list(1);
          } else {
            this.data_list_loding_status = 0;
            this.data_list_loding_msg = res.data.msg;
          }
          
          const { category_id = 0, keywords = '' } = this.params;
          this.share_info = {
            path: '/pages/fcc/classinfo/companycard/companycard',
            query: `category_id=${category_id}&keywords=${keywords}`
          };
        },
        fail: () => {
          uni.stopPullDownRefresh();
          this.data_list_loding_status = 2;
          this.data_list_loding_msg = '网络请求出错';
        }
      });
    },
    
    search_input_event(e) {
      const keywords = e.detail.value;
      /*if (!keywords) {
        app.globalData.showToast('请输入搜索关键字');
        return false;
      }*/
      
      this.post_data.wd = keywords;
      this.resetAndReload();
    },
    
    request_map_handle() {
      const post_data = {
        ...this.post_data,
        page: this.data_page,
        category_id: this.selectedIndustry,
        city_id: this.site_for_led == 1 ? 0 : this.city_id,
        top_ids: this.top_ids
      };
      
      const sortMap = {
        distance: { field: 'distance', sort: 'asc' },
        id: { field: 'id', sort: 'asc' },
        default: { field: 'default', sort: 'asc' }
      };
      
      const sort = sortMap[this.selectedSort];
      if (sort) {
        post_data.order_by_field = sort.field;
        post_data.order_by_type = sort.sort;
      }

      return post_data;
    },
    
    get_data_list(is_mandatory = 0) {
      if (!is_mandatory && this.data_bottom_line_status) {
        uni.stopPullDownRefresh();
        return false;
      }
      
      if (this.data_is_loading == 1) {
        return false;
      }
      
      this.data_is_loading = 1;
      this.data_list_loding_status = 1;
      
      uni.showLoading({ title: '加载中...' });
      
      const post_data = this.request_map_handle();
      
      uni.request({
        url: app.globalData.get_request_url('card', 'index', 'classinfo'),
        method: 'POST',
        data: post_data,
        success: (res) => {console.log(res);
          if (res.data.code == 0) {
            this.handleDataListSuccess(res);
          } else {
            if (res.data.code == 6699) {
              app.globalData.alert({
                title: this.$t('fengcheche.cutprice.wenxin_tips_title'),
                msg: res.data.msg,
                confirm_text: '去定位',
                confirm_color: '#0682fc',
                object: this,
                method: 'location_tips'
              });
            } else {
              app.globalData.showToast(res.data.msg);
            }
          }
        },
        fail: () => {
          this.handleDataListError();
        },
        complete: () => {
          uni.hideLoading();
          uni.stopPullDownRefresh();
          this.data_is_loading = 0;
        }
      });
    },
	
	location_tips(params){
		if(params['alert_status'] == 1)
		{
			setTimeout(() => {
				uni.navigateTo({
					url: '/pages/common/open-setting-location/open-setting-location'
				});
			}, 300);
		}else{
			// 拒绝，则回到默认筛选方式
			// 默认推荐排序
			this.selectedSort = this.sortOptions[2].value;
			
			this.resetAndReload();
		}
	},
    
    handleDataListSuccess(res) {
      if (res.data.code == 0) {
        const data = res.data.data;
        
        if (data.data.length > 0) {
          const newList = this.data_page <= 1 
            ? data.data 
            : [...this.data_list, ...data.data];
          
          Object.assign(this, {
            data_list: newList,
            data_total: data.total,
            data_page_total: data.page_total,
            data_list_loding_status: 3,
            data_list_loding_msg: '',
            data_page: this.data_page + 1,
            data_bottom_line_status: this.data_page > data.page_total
          });
        } else {
          this.data_list_loding_status = 0;
          this.data_total = 0;
          
          if (this.data_page <= 1) {
            this.data_list = [];
            this.data_bottom_line_status = false;
          }
        }
      } else {
        this.data_list_loding_status = 0;
        this.data_list_loding_msg = res.data.msg;
      }
    },
    
    handleDataListError() {
      this.data_list_loding_status = 2;
      this.data_list_loding_msg = '网络请求出错';
    },
    
    url_event(e) {
      app.globalData.url_event(e);
    },
    
    toggleSortFilter() {
      this.showSortFilter = !this.showSortFilter;
    },
    
    closeSortFilter() {
      this.showSortFilter = false;
    },
    
    goToCitySelect() {
      uni.navigateTo({
        url: '/pages/fcc/classinfo/chose-city/chose-city'
      });
    },
    
    toggleIndustryFilter() {
      this.showIndustryFilter = !this.showIndustryFilter;
    },
    
    closeIndustryFilter() {
      this.showIndustryFilter = false;
    },
	
	handleToggleFavorite(data) {
      const { id, is_soucang } = data;
      
      const topItem = this.top_data_list.find(item => item.id === id);
      if (topItem) {
        topItem.is_soucang = is_soucang;
        this.$set(this.top_data_list, this.top_data_list.indexOf(topItem), topItem);
      }

      const listItem = this.data_list.find(item => item.id === id);
      if (listItem) {
        listItem.is_soucang = is_soucang;
        this.$set(this.data_list, this.data_list.indexOf(listItem), listItem);
      }
    }
  }
}
</script>

<style scoped>
/* 基础样式 */
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.page-bottom-fixed {
  padding-bottom: 100rpx;
}

/* 头部样式 */
.header {
  background-color: #10b981;
  padding: 20rpx;
  position: sticky;
  top: 0;
  z-index: 100;
}

/* 搜索框 */
.search {
  width: 100%;
}

.search-content {
  display: flex;
  align-items: center;
  background-color: white;
  padding: 15rpx 20rpx;
  border-radius: 10rpx;
}

.bg-gray {
  background-color: #f5f5f5;
}

.flex-row {
  display: flex;
  flex-direction: row;
}

.spi {
  margin-right: 10rpx;
}

.search-content input {
  flex: 1;
  font-size: 28rpx;
}

/* 新的筛选区域样式 - 横向布局 */
.filter-section {
  background-color: white;
  position: sticky;
  top: 100rpx;
  z-index: 99;
  border-bottom: 1px solid #e5e5e5;
}

/* 行业分类横向滚动 */
.industry-scroll {
  white-space: nowrap;
  border-bottom: 1px solid #f0f0f0;
}

.industry-list {
  display: inline-flex;
  padding: 20rpx 20rpx;
}

.industry-item {
  display: inline-block;
  padding: 12rpx 28rpx;
  margin-right: 20rpx;
  font-size: 28rpx;
  color: #666;
  background-color: #f5f5f5;
  border-radius: 30rpx;
  white-space: nowrap;
  transition: all 0.3s;
}

.industry-item.active {
  color: white;
  background-color: #10b981;
}

/* 智能排序横向平铺 */
.sort-list {
  display: flex;
  align-items: center;
  justify-content: space-around;
  padding: 20rpx 0;
}

.sort-item {
  flex: 1;
  text-align: center;
  font-size: 28rpx;
  color: #666;
  padding: 10rpx;
  position: relative;
  transition: all 0.3s;
}

.sort-item.active {
  color: #10b981;
  font-weight: bold;
}

.sort-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 40rpx;
  height: 4rpx;
  background-color: #10b981;
  border-radius: 2rpx;
}


/* 添加筛选栏样式 */
.filter-bar {
  display: flex;
  align-items: center;
  background-color: white;
  padding: 20rpx 30rpx;
  border-bottom: 1px solid #e5e5e5;
  position: sticky;
  top: 100rpx;
  z-index: 99;
}

.filter-item {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  color: #333;
  padding: 10rpx;
  position: relative;
}

.arrow-down {
  width: 0;
  height: 0;
  border-left: 8rpx solid transparent;
  border-right: 8rpx solid transparent;
  border-top: 10rpx solid #999;
  margin-left: 10rpx;
}

.arrow-down-small {
  width: 0;
  height: 0;
  border-left: 8rpx solid transparent;
  border-right: 8rpx solid transparent;
  border-top: 10rpx solid #999;
  margin-left: 10rpx;
}

.filter-popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 999;
  display: flex;
  justify-content: center;
  padding-top: 200rpx;
}

.filter-popup-content {
  background-color: white;
  width: 90%;
  max-height: 600rpx;
  border-radius: 16rpx;
  overflow-y: auto;
  padding: 20rpx 0;
}

.filter-option {
  padding: 25rpx 40rpx;
  font-size: 30rpx;
  color: #333;
  border-bottom: 1px solid #f5f5f5;
}

.filter-option.active {
  color: #10b981;
  background-color: #ecfdf5;
}

.filter-option:last-child {
  border-bottom: none;
}

/* 内容区域 */
.padding-top-main {
  padding-top: 20rpx;
}
</style>
